package com.project.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component //申明该类为spring组件类
@Aspect //申明该类为切面类
public class ServiceAspect {

    @Before("execution(* com.project.service..*.*(..))")
    public void beforeMethod(){
        System.out.println("前置通知");
    }
//    @AfterReturning("execution(* com.project.service..*.*(..))")
    @After("execution(* com.project.service..*.*(..))")
    public void afterMethod(){
        System.out.println("后通知");
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint jp){
        try {
            System.out.println("环绕前");
            //执行目标方法，得到方法执行后的返回值
            Object returnObj = jp.proceed();
            //得到目标对象
//            Object targetObj = jp.getTarget();
            System.out.println("环绕后");
            return returnObj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
    @AfterThrowing(value = "execution(* com.project.service..*.*(..))",
            throwing = "e")//throwing = "e"表示目标方法抛出的异常由形参e接收
    public void throwException(JoinPoint jp, Exception e){
        //得到目标对象
        Object targetObj = jp.getTarget();
        //得到目标方法的名称
        String methodName = jp.getSignature().getName();
        System.out.println(targetObj.getClass().getName()+"的"+methodName+"()方法，抛出"+
                e.getClass().getName());
    }
}
